package com.ziq.zcamp.dialog

import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import androidx.core.view.isVisible
import com.blankj.utilcode.util.SpanUtils
import com.ziq.base.base.BaseDialog
import com.ziq.zcamp.databinding.DialogAlertBinding
import com.ziq.base.extension.binding
import com.ziq.base.extension.click

class AlertDialog(context: Context, val gravity : Int = Gravity.CENTER) : BaseDialog(context) {

    private val binding: DialogAlertBinding by binding()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.root
    }

    override fun initGravity(): Int {
        return gravity
    }


    fun setContainerLayout(layout:(layoutParams: FrameLayout.LayoutParams,view : FrameLayout) -> Unit): AlertDialog{
        if(binding.container.layoutParams is FrameLayout.LayoutParams){
            val lp = binding.container.layoutParams as FrameLayout.LayoutParams
            layout.invoke(lp,binding.container)
            binding.container.layoutParams = lp
        }
        return this
    }

    fun setTitle(text:(span : SpanUtils)->Unit) : AlertDialog{
        binding.title.visibility = View.VISIBLE
        val span = SpanUtils.with(binding.title)
        text.invoke(span)
        span.create()
        return this
    }

    fun setContent(text: (span : SpanUtils)->Unit, isCenter: Boolean = false) : AlertDialog{
        binding.content.visibility = View.VISIBLE
        binding.content.gravity = if(isCenter) Gravity.CENTER else Gravity.LEFT
        val span = SpanUtils.with(binding.content)
        text.invoke(span)
        span.create()
        return this
    }

    fun setCancelButton(text:(span : SpanUtils)->Unit, action: (dialog : Dialog)->Unit) : AlertDialog{
        binding.btnLeft.click {
            action.invoke(this)
        }
        val span = SpanUtils.with(binding.btnLeft)
        text.invoke(span)
        span.create()
        return this
    }

    fun setConfirmButton(text:(span : SpanUtils)->Unit, action: (dialog : Dialog)->Unit) : AlertDialog{
        binding.btnRight.visibility = View.VISIBLE
        binding.btnRight.click {
            action.invoke(this)
        }
        val span = SpanUtils.with(binding.btnRight)
        text.invoke(span)
        span.create()
        return this
    }

    fun setCloseShow(show : Boolean , action: (dialog: Dialog) -> Unit): AlertDialog {
        binding.close.isVisible = show
        binding.close.click {
            action.invoke(this)
        }
        return this
    }


    fun setCancelListener(action: DialogInterface.OnCancelListener) : AlertDialog{
        setOnCancelListener(action)
        return this
    }
}